﻿using Timer = System.Windows.Forms.Timer;

namespace AntdTest.Forms
{
    public partial class Loading : AntdUI.Window
    {
        readonly Timer timer = new() { Interval = 200 };
        DateTime timeStart = DateTime.Now;
        string _caption = "加载中，请稍候...";

        /// <summary>
        /// 总耗时（秒）
        /// </summary>
        public double ElapsedSeconds;

        public Loading()
        {
            InitializeComponent();

            Text = $"{Globals.App.Name} - 加载器";
            FormBorderStyle = FormBorderStyle.FixedSingle;
            Resizable = false;
            StartPosition = FormStartPosition.CenterParent;
            ShowInTaskbar = false;

            VisibleChanged += Loading_VisibleChanged;

            spin1.Text = $"[{Math.Floor((DateTime.Now - timeStart).TotalSeconds)} 秒] {_caption}";
            timer.Tick += Timer_Tick;
        }

        #region 单例模式
        private static Loading? _instance;
        public static Loading Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Loading();
                }
                return _instance;
            }
        }
        #endregion

        private void Loading_VisibleChanged(object? sender, EventArgs e)
        {
            if (Visible)
            {
                timeStart = DateTime.Now;
                timer.Start();
                Helpers.Antd.InheritTheme(this);
            }
            else
            {
                timer.Stop();
            }
        }

        private void Timer_Tick(object? sender, EventArgs e)
        {
            ElapsedSeconds = Math.Ceiling((DateTime.Now - timeStart).TotalSeconds);
            spin1.Text = $"[{ElapsedSeconds} 秒] {_caption}";
        }

        /// <summary>
        /// 设置加载器文本
        /// </summary>
        /// <param name="caption">加载器文本</param>
        public void SetCaption(string caption = "加载中，请稍候...")
        {
            _caption = caption;
        }
    }
}